package com.example.ftp4j_demo2;

import java.io.File;

import it.sauronsoftware.ftp4j.FTPClient;

public class upload {

		   
	    private FTPClient client = new FTPClient();
	   
	    private String ftpHost;
	    private int ftpPort = 21;
	    private String ftpUser;
	    private String ftpPasswd;
	   



		public upload(String ftpHost, int ftpPort, String ftpUser,
	            String ftpPasswd) {
	     
	        this.ftpHost = ftpHost;
	        this.ftpPort = ftpPort;
	        this.ftpUser = ftpUser;
	        this.ftpPasswd = ftpPasswd;
	        
	    }

	    public  FTPClient openConnection()throws Exception{
    	  
	           client.connect(ftpHost, ftpPort);
	           client.login(ftpUser, ftpPasswd);
	           
	           return client;

	    }

	    public boolean closeConnection() {
	            if ( null != client && client.isConnected()) {
	              try {
	                    client.disconnect(true);
	                    return true;
	                    } catch (Exception e) {
	                       e.printStackTrace();
	                       return false;
	                    }
	            }
	            return true;
	    }
	    
	    public void uploadfile(String localfilePath, String remoteFolderPath) {
            File localfile = new File(localfilePath);         
            try {
                openConnection();
                // ftp client 执行CD指令
                client.changeDirectory(remoteFolderPath);

                // 校验本地上传文件
                if (!localfile.exists())
                    throw new RuntimeException("上传文件不存在");
                if (!localfile.isFile())
                    throw new RuntimeException("上传文件是目录,不是文件");

                client.upload(localfile);
                client.changeDirectory("/");

            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                   closeConnection();
            }
    }


}
